package com.tuyrt.`as`.proj.main.fragment.profile

import android.graphics.Typeface
import android.os.Bundle
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import com.tuyrt.`as`.proj.common.ui.component.HiBaseFragment
import com.tuyrt.`as`.proj.common.ui.view.loadCircle
import com.tuyrt.`as`.proj.common.ui.view.loadCorner
import com.tuyrt.`as`.proj.main.R
import com.tuyrt.`as`.proj.main.biz.account.AccountManager
import com.tuyrt.`as`.proj.main.http.ApiFactory
import com.tuyrt.`as`.proj.main.http.api.AccountApi
import com.tuyrt.`as`.proj.main.model.CourseNotice
import com.tuyrt.`as`.proj.main.model.Notice
import com.tuyrt.`as`.proj.main.model.UserProfile
import com.tuyrt.`as`.proj.main.route.HiRoute
import com.tuyrt.hi.library.restful.HiCallback
import com.tuyrt.hi.library.restful.HiResponse
import com.tuyrt.hi.library.util.AppGlobals
import com.tuyrt.hi.library.util.HiDisplayUtil
import com.tuyrt.hi.ui.banner.core.HiBannerMo
import kotlinx.android.synthetic.main.fragment_profile.*

/**
 * author: Administrator on 2021/4/29.
 * desc:
 */
class ProfileFragment : HiBaseFragment() {

    private val REQUEST_CODE_LOGIN_PROFILE: Int = 1001

    override fun getLayoutId(): Int {
        return R.layout.fragment_profile
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        queryLoginUserData()

        queryCourseNotice()
    }

    private fun queryCourseNotice() {
        ApiFactory.create(AccountApi::class.java).notice().enqueue(object : HiCallback<CourseNotice> {
            override fun onSuccess(response: HiResponse<CourseNotice>) {
                if (response.data != null && response.data!!.total > 0) {
                    notify_count.text = response.data!!.total.toString()
                    notify_count.visibility = View.VISIBLE
                }
            }

            override fun onFailed(throwable: Throwable) {
            }
        })
    }

    private fun queryLoginUserData() {
        AccountManager.getUserProfile(this,  { profile ->
            if (profile != null) {
                updateUI(profile)
            } else {
                toast(getString(R.string.fetch_user_profile_failed))
            }
        }, onlyCache = false)
    }

    private fun updateUI(userProfile: UserProfile) {
        user_name.text = if (userProfile.isLogin) userProfile.userName else getString(R.string.profile_not_login)
        login_desc.text = if (userProfile.isLogin)
            getString(R.string.profile_login_desc_welcome_back)
        else
            getString(R.string.profile_login_desc)

        if (userProfile.isLogin) {
            user_avatar.loadCircle(userProfile.userIcon)
        } else {
            user_avatar.setImageResource(R.drawable.ic_avatar_default)
            user_avatar.setOnClickListener {
                AccountManager.login(context) { success ->
                    queryLoginUserData()
                }
            }
        }

        tab_item_collection.text = spannableTabItem(userProfile.favoriteCount, getString(R.string.profile_tab_item_collection))
        tab_item_history.text = spannableTabItem(userProfile.browseCount, getString(R.string.profile_tab_item_history))
        tab_item_learn.text = spannableTabItem(userProfile.learnMinutes, getString(R.string.profile_tab_item_learn))

        updateBanner(userProfile.bannerNoticeList)
    }

    private fun updateBanner(bannerNoticeList: List<Notice>?) {
        if (bannerNoticeList == null || bannerNoticeList.isEmpty()) return

        val models = mutableListOf<HiBannerMo>()
        bannerNoticeList.forEach {
            val hiBannerMo = object : HiBannerMo() {}
            hiBannerMo.url = it.cover
            models.add(hiBannerMo)
        }

        hi_banner.setBannerData(R.layout.layout_profile_banner_item, models)
        hi_banner.setBindAdapter { viewHolder, mo, position ->
            if (viewHolder == null) return@setBindAdapter
            val imageView = viewHolder.findViewById<ImageView>(R.id.banner_item_imageview)
            imageView.loadCorner(mo.url, HiDisplayUtil.dp2px(10f, resources))
        }
        hi_banner.setOnBannerClickListener { viewHolder, bannerMo, position ->
            HiRoute.startActivity4Browser(bannerNoticeList[position].url)
        }
        hi_banner.visibility = View.VISIBLE
    }

    private fun spannableTabItem(topText: Int, bottomText: String): CharSequence? {
        val spanStr = topText.toString()
        val ssb = SpannableStringBuilder()
        val ssTop = SpannableString(spanStr)

        val spanFlag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        ssTop.setSpan(
            ForegroundColorSpan(ContextCompat.getColor(AppGlobals.get()!!, R.color.color_000)),
            0,
            ssTop.length,
            spanFlag
        )
        ssTop.setSpan(AbsoluteSizeSpan(18, true), 0, ssTop.length, spanFlag)
        ssTop.setSpan(StyleSpan(Typeface.BOLD), 0, ssTop.length, spanFlag)

        ssb.append(ssTop)
        ssb.append(bottomText)
        return ssb
    }

}